package org.dxy.domain.game.model.aggregate.impl;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.dxy.domain.game.adapter.event.EventQueue;
import org.dxy.domain.game.adapter.event.GameInitializedEvent;
import org.dxy.domain.game.command.GameStartCommand;
import org.dxy.domain.game.command.SideSwapCommand;
import org.dxy.domain.game.database.GameDatabase;
import org.dxy.domain.game.model.aggregate.GameAggregate;
import org.dxy.domain.game.model.entity.GameEntity;
import org.dxy.domain.game.model.entity.PieceEntity;
import org.dxy.types.enums.*;
import org.dxy.domain.game.model.entity.PlayerEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Getter
@Service
public class GameAggregateImpl implements GameAggregate {
    // 使用内存作为存储，可以替换为数据库
    @Autowired
    private GameDatabase gameDatabase;

    // 游戏ID，用于唯一标识一个游戏实例
    private Long gameId; // 游戏id

    // 棋子ID，用于唯一标识一个棋子
    private Long pieceId; // 棋子id

    // 当前下棋的玩家id
    private Long currentPlayerId; // 玩家id

    // 游戏是否被暂停
    private boolean isGamePaused; // 游戏是否被暂停

    // 是否游戏胜利
    private boolean isGameWon; // 是否游戏胜利

    // 是否游戏结束
    private boolean isGameEnded; // 是否游戏结束

    // 是否开始游戏
    private boolean isGameStarted; // 是否开始游戏

    // 游戏当前回合数
    private int currentRoundNumber; // 游戏当前回合数

    // 悔棋数
    private int regretMoveCount; // 悔棋数

    // 是否可以悔棋
    private boolean canRegretMove; // 是否可以悔棋

    // 是否可以换边（通常用于象棋、围棋等双人对弈游戏）
    private boolean canSwitchSides; // 是否可以换边

    // 是否发起请求（如暂停、悔棋、换边、和棋、投降等）
    private boolean hasRequestBeenSent; // 是否发起请求

    // 请求是否被接受（对方玩家是否接受了请求）
    private boolean isRequestAccepted; // 请求是否被接受

    // 请求方案，枚举类型，包括游戏暂停、悔棋、换边、和棋、投降等
    private RequestTypeEnum requestType; // 请求方案(游戏暂停，悔棋，换边，和棋，投降)

    // 玩家倒计时，默认20秒
    private int playerCountdown; // 玩家倒计时（默认20s）

    @Override
    public void handle(EventQueue eventQueue, GameStartCommand gameStartCommand) {

        Map<Long, PlayerEntity> playerEntityMap = gameDatabase.getPlayerEntityMap();
        Map<Long, PieceEntity> pieceEntityMap = gameDatabase.getPieceEntityMap();
        GameEntity gameEntity = GameEntity.builder().gameId(1L)
                .build();

        this.gameId = gameEntity.getGameId();

        gameDatabase.addGame(gameEntity);

        PlayerEntity player1 = PlayerEntity.builder()
                .playerId(1L)
                .playerSide(PlayerSideEnum.RED)
                .name("Tom")
                .status(PlayerStatusEnum.IN_GAME)
                .build();

        PlayerEntity player2 = PlayerEntity.builder()
                .playerId(2L)
                .playerSide(PlayerSideEnum.BLACK)
                .name("Bob")
                .status(PlayerStatusEnum.IN_GAME)
                .build();
        // 默认第一次下棋的玩家id为红色方id
        this.currentPlayerId = player1.getPlayerId();

                // 1.初始化两个玩家
        playerEntityMap.put(player1.getPlayerId(), player1);
        playerEntityMap.put(player2.getPlayerId(), player2);

        this.initializePieces();

        pieceEntityMap.forEach((pieceId, pieceEntity) ->{
            if (pieceId >= 1 && pieceId <= 16) {
                pieceEntity.setPlayerId(player1.getPlayerId());
            } else if (pieceId >= 21 && pieceId <= 36) {
                pieceEntity.setPlayerId(player2.getPlayerId());
            }
        });

        GameInitializedEvent gameInitializedEvent = GameInitializedEvent.builder().gameId(1L).build();
        eventQueue.enqueue(gameInitializedEvent);
    }

    @Override
    public void handle(EventQueue eventQueue, SideSwapCommand sideSwapCommand) {
//        Long gameId1 = sideSwapCommand.getGameId();
        Long playerId = sideSwapCommand.getPlayerId();
        for (PlayerEntity playerEntity : gameDatabase.getAllPlayer()) {
            if(playerEntity.getPlayerId() != playerId){
                this.currentPlayerId = playerId;
            }
        }
        this.swapSide();
    }


    public void swapSide() {
        Map<Long, PieceEntity> pieceEntityMap = gameDatabase.getPieceEntityMap();
        Map<Long, PieceEntity> newPieceMap = new HashMap<>();

        for (Map.Entry<Long, PieceEntity> entry : pieceEntityMap.entrySet()) {
            PieceEntity oldPiece = entry.getValue();

            // 创建一个新棋子，并交换位置
            PieceEntity newPiece = PieceEntity.builder()
                    .pieceId(oldPiece.getPieceId())
                    .row(8 - oldPiece.getRow()) // 交换行
                    .column(9 - oldPiece.getColumn()) // 交换列（如果有需要）
                    .isCaptured(oldPiece.isCaptured())
                    .pieceName(oldPiece.getPieceName())
                    .imagePath(oldPiece.getImagePath()) // 更新棋子图片
                    .pieceColorEnum(oldPiece.getPieceColorEnum() == PieceColorEnum.RED
                            ? PieceColorEnum.BLACK
                            : PieceColorEnum.RED) // 交换颜色
                    .build();

            newPieceMap.put(newPiece.getPieceId(), newPiece);
        }

        // 替换原来的 pieceEntityMap
        gameDatabase.setPieceEntityMap(newPieceMap);
    }



    private void initializePieces() {
        Map<Long, PieceEntity> pieceEntityMap = gameDatabase.getPieceEntityMap();

        // 创建红方棋子并放入 Map 中
        pieceEntityMap.put(1L, PieceEntity.builder()
                .pieceId(1L)
                .row(0)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ROOK)
                .imagePath("images/红车.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(2L, PieceEntity.builder()
                .pieceId(2L)
                .row(1)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.KNIGHT)
                .imagePath("images/红马.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(3L, PieceEntity.builder()
                .pieceId(3L)
                .row(2)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.MINISTER)
                .imagePath("images/红相.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(4L, PieceEntity.builder()
                .pieceId(4L)
                .row(3)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ADVISOR)
                .imagePath("images/红士.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(5L, PieceEntity.builder()
                .pieceId(5L)
                .row(4)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.KING)
                .imagePath("images/红帅.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(6L, PieceEntity.builder()
                .pieceId(6L)
                .row(5)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ADVISOR)
                .imagePath("images/红士.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(7L, PieceEntity.builder()
                .pieceId(7L)
                .row(6)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.MINISTER)
                .imagePath("images/红相.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(8L, PieceEntity.builder()
                .pieceId(8L)
                .row(7)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.KNIGHT)
                .imagePath("images/红马.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(9L, PieceEntity.builder()
                .pieceId(9L)
                .row(8)
                .column(0)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ROOK)
                .imagePath("images/红车.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(10L, PieceEntity.builder()
                .pieceId(10L)
                .row(1)
                .column(2)
                .isCaptured(false)
                .pieceName(PieceNameEnum.CANNON)
                .imagePath("images/红炮.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(11L, PieceEntity.builder()
                .pieceId(11L)
                .row(7)
                .column(2)
                .isCaptured(false)
                .pieceName(PieceNameEnum.CANNON)
                .imagePath("images/红炮.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(12L, PieceEntity.builder()
                .pieceId(12L)
                .row(0)
                .column(3)
                .isCaptured(false)
                .pieceName(PieceNameEnum.PAWN)
                .imagePath("images/红兵.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(13L, PieceEntity.builder()
                .pieceId(13L)
                .row(2)
                .column(3)
                .isCaptured(false)
                .pieceName(PieceNameEnum.PAWN)
                .imagePath("images/红兵.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(14L, PieceEntity.builder()
                .pieceId(14L)
                .row(4)
                .column(3)
                .isCaptured(false)
                .pieceName(PieceNameEnum.PAWN)
                .imagePath("images/红兵.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(15L, PieceEntity.builder()
                .pieceId(15L)
                .row(6)
                .column(3)
                .isCaptured(false)
                .pieceName(PieceNameEnum.PAWN)
                .imagePath("images/红兵.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());

        pieceEntityMap.put(16L, PieceEntity.builder()
                .pieceId(16L)
                .row(8)
                .column(3)
                .isCaptured(false)
                .pieceName(PieceNameEnum.PAWN)
                .imagePath("images/红兵.gif")
                .pieceColorEnum(PieceColorEnum.RED)
                .build());


        // 创建黑方棋子并放入 Map 中
        pieceEntityMap.put(21L, PieceEntity.builder()
                .pieceId(21L)
                .row(0)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ROOK)
                .imagePath("images/黑车.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(22L, PieceEntity.builder()
                .pieceId(22L)
                .row(1)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.KNIGHT)
                .imagePath("images/黑马.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(23L, PieceEntity.builder()
                .pieceId(23L)
                .row(2)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.MINISTER)
                .imagePath("images/黑象.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(24L, PieceEntity.builder()
                .pieceId(24L)
                .row(3)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ADVISOR)
                .imagePath("images/黑士.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(25L, PieceEntity.builder()
                .pieceId(25L)
                .row(4)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.KING)
                .imagePath("images/黑将.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(26L, PieceEntity.builder()
                .pieceId(26L)
                .row(5)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ADVISOR)
                .imagePath("images/黑士.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(27L, PieceEntity.builder()
                .pieceId(27L)
                .row(6)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.MINISTER)
                .imagePath("images/黑象.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(28L, PieceEntity.builder()
                .pieceId(28L)
                .row(7)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.KNIGHT)
                .imagePath("images/黑马.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(29L, PieceEntity.builder()
                .pieceId(29L)
                .row(8)
                .column(9)
                .isCaptured(false)
                .pieceName(PieceNameEnum.ROOK)
                .imagePath("images/黑车.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(30L, PieceEntity.builder()
                .pieceId(30L)
                .row(1)
                .column(7)
                .isCaptured(false)
                .pieceName(PieceNameEnum.CANNON)
                .imagePath("images/黑炮.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(31L, PieceEntity.builder()
                .pieceId(31L)
                .row(7)
                .column(7)
                .isCaptured(false)
                .pieceName(PieceNameEnum.CANNON)
                .imagePath("images/黑炮.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(32L, PieceEntity.builder()
                .pieceId(32L)
                .row(0)
                .column(6)
                .isCaptured(false)
                .pieceName(PieceNameEnum.SOLDIER)
                .imagePath("images/黑卒.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(33L, PieceEntity.builder()
                .pieceId(33L)
                .row(2)
                .column(6)
                .isCaptured(false)
                .pieceName(PieceNameEnum.SOLDIER)
                .imagePath("images/黑卒.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(34L, PieceEntity.builder()
                .pieceId(34L)
                .row(4)
                .column(6)
                .isCaptured(false)
                .pieceName(PieceNameEnum.SOLDIER)
                .imagePath("images/黑卒.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(35L, PieceEntity.builder()
                .pieceId(35L)
                .row(6)
                .column(6)
                .isCaptured(false)
                .pieceName(PieceNameEnum.SOLDIER)
                .imagePath("images/黑卒.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());

        pieceEntityMap.put(36L, PieceEntity.builder()
                .pieceId(36L)
                .row(8)
                .column(6)
                .isCaptured(false)
                .pieceName(PieceNameEnum.SOLDIER)
                .imagePath("images/黑卒.gif")
                .pieceColorEnum(PieceColorEnum.BLACK)
                .build());
    }


}
